package com.qqq.chatservice.config;

import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.util.List;
import java.util.Map;

@Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator {
    /**
     * 这个类注册每个加了 @ServerEndpoint 的 spring bean节点，算是 spring 整合
     * websocket的⼀个体现，
     * 没有的话会报404
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    /**
     * 建⽴握手时，连接前的操作，可以获取到源信息，并且传递给Session
     */
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest
            request, HandshakeResponse response) {
        //设置用户信息
        Map<String, List<String>> headers = request.getHeaders();
        List<String> authorizations = headers.get("Authorization");
        if (authorizations == null || authorizations.isEmpty()) {
        // 如果请求头不符合要求，则拒绝握手
            throw new RuntimeException("请求头不符合要求，缺少Authorization信息");
        }
        // 向userProperties中设置Header，连接后才能获取到
        final Map<String, Object> userProperties = sec.getUserProperties();
        userProperties.put("Authorization", authorizations.get(0));
    }
}
